<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" v-show="$permiss[438]" :xs="24">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select v-model="page.adminUserId" @change="tenantChange" style="width: 100%" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-show="$permiss[439]" :xs="24">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户类型')" prop="isRepeatedBorrowing">
          <el-select style="width: 100%" v-model="page.isRepeatedBorrowing" clearable>
            <el-option v-for="item in userType" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('打款日期')" prop="timeValue">
          <el-date-picker
              v-show="activeName === 'day'"
              v-model="dayTimeValue"
              style="width: 100%"
              type="daterange"
              unlink-panels
              :clearable="false"
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')">i
          </el-date-picker>
          <div v-show="activeName === 'week'">
            <el-col :span="11" style="padding: 0 5px">
              <el-date-picker
                  style="width: 100%;"
                  v-model="weekStart"
                  type="week"
                  :picker-options="{'firstDayOfWeek': 1}"
                  :format="'yyyy' + ' ' + $t('第') + ' ' + 'WW' + ' ' + $t('周')"
                  @change="changeWeekValue($event,'start')"
                  :placeholder="$t('开始周')">
              </el-date-picker>
            </el-col>
            <el-col :span="1" style="line-height: 32px;padding: 0;text-align: center">
              <span>~</span>
            </el-col>
            <el-col :span="11" style="padding: 0 5px">
              <el-date-picker
                  style="width: 100%;"
                  v-model="weekEnd"
                  type="week"
                  :picker-options="{'firstDayOfWeek': 1}"
                  :format="'yyyy' + ' ' + $t('第') + ' ' + 'WW' + ' ' + $t('周')"
                  @change="changeWeekValue($event,'end')"
                  :placeholder="$t('结束周')">
              </el-date-picker>
            </el-col>
          </div>
          <el-date-picker
              v-show="activeName === 'month'"
              v-model="monthTimeValue"
              type="monthrange"
              style="width: 100%"
              :clearable="false"
              value-format="yyyy-MM"
              unlink-panels
              range-separator="~"
              :start-placeholder="$t('开始月份')"
              :end-placeholder="$t('结束月份')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :label="$t('日报表')" name="day"></el-tab-pane>
        <el-tab-pane :label="$t('月报表')" name="month"></el-tab-pane>
        <div style="text-align: right;margin-bottom: 10px" v-show="$permiss[788]">
          <el-button type="primary" @click="exportsExcel" :loading="exportsLoading">{{ $t('导出') }}</el-button>
        </div>
        <Table :loading="loading" max-height="600px" :page="page" :table-column="tableColumn" :table-data="tableData"
               @handleSizeChange="handleSizeChange"
               @handleCurrentChange="handleCurrentChange"/>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import {export_json_to_excel} from "@/utils/exportExcel";
import dayjs from 'dayjs'
import {dateFormat, dateFormatSection, defaultTimeDate} from "@/utils/tools";
import {
  fetchFinancialProfits,
  financialProfitsTotal,
  financialProfitsExport,
  financialProfitsMeanValue
} from '@/api/finance'
import {selectProduct, selectTenant} from "@/api/system";

export default {
  name: 'financeProfit',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        type: 1,
      },
      monthPage: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
        type: 2,
      },
      dayTimeValue: defaultTimeDate(30),
      monthTimeValue: defaultTimeDate(1, 'YYYY-MM'),
      weekStart: '',
      weekEnd: '',
      tenantList: [],
      productList: [],
      tableData: [],
      dayTableData: [],
      monthTableData: [],
      tableColumn: [
        {label: this.$t('打款日期'), prop: 'time', width: 100, fixed: 'left'},
        {label: this.$t('打款数'), prop: 'count', minWidth: 100,},
        {label: this.$t('合同金额'), prop: 'passAmount', minWidth: 120,},
        {label: this.$t('打款本金'), prop: 'dealAmount', minWidth: 120,},
        {label: this.$t('应还金额'), prop: 'shouldAmount', minWidth: 120,},
        {label: this.$t('应还利息'), prop: 'shouldInterest', minWidth: 120,},
        {label: this.$t('应还罚息'), prop: 'shouldOverdue', minWidth: 120,},
        {label: this.$t('实还笔数'), prop: 'refundNumber', minWidth: 120},
        {label: this.$t('实还金额'), prop: 'refundAmount', minWidth: 120},
        {label: this.$t('实还合同金额'), prop: 'refundPrincipal', width: 120},
        {label: this.$t('实还利息'), prop: 'refundInterest', minWidth: 120},
        {label: this.$t('实还罚息'), prop: 'refundOverdue', minWidth: 120},
        {label: this.$t('展期笔数'), prop: 'delayNumber', minWidth: 120},
        {label: this.$t('展期手续费'), prop: 'delayAmount', minWidth: 120},
        {label: this.$t('逾期合同金额'), prop: 'overduePrincipal', width: 150},
        {label: this.$t('减免笔数'), prop: 'remissionNumber', minWidth: 120},
        {label: this.$t('减免金额'), prop: 'remissionAmount', minWidth: 120},
        {label: this.$t('还款总额'), prop: 'refundTotalAmount', minWidth: 120},
        {label: this.$t('盈亏总额'), prop: 'profitAndLossAmount', minWidth: 120},
        {label: this.$t('本金收益率'), prop: 'principalEarningsRate', minWidth: 120},
        {label: this.$t('营业额收益率'), prop: 'turnoverEarningsRate', minWidth: 120},
      ],
      activeName: 'day',
      weekFormat: '',
      userType: [
        {label: this.$t('新客'), value: 0},
        {label: this.$t('老客'), value: 1},
      ],
      loading: false,
      exportsLoading: false,
      financialProfitsTotal: [],
      financialProfitsTotalColumn: [
        {label: this.$t('打款总额'), prop: 'dealAmount', minWidth: 150},
        {label: this.$t('打款订单数'), prop: 'cardPayOrderNum', minWidth: 150},
        {label: this.$t('还款总额'), prop: 'refundTotalAmount', minWidth: 150},
        {label: this.$t('还款订单数'), prop: 'refundOrderNum', minWidth: 150},
        {label: this.$t('盈亏总额'), prop: 'profitAndLossAmount', minWidth: 150},
      ]
    }
  },
  mounted() {
    this.getTableData()
    selectTenant().then(res => {
      this.tenantList = res.data
    })
    selectProduct().then(res => {
      this.productList = res.data
    })
  },
  methods: {
    async getTableData() {
      this.loading = true
      const timeValue = this.activeName === 'day' ? dateFormatSection(this.dayTimeValue) : this.formatMonthDate(this.monthTimeValue)
      const [datetimeStart, datetimeEnd] = timeValue
      const params = {
        datetimeStart, datetimeEnd,
        ...this.page
      }
      delete params.timeValue
      const p1 = fetchFinancialProfits(params)
      const p2 = financialProfitsTotal(params)
      const p3 = financialProfitsMeanValue(params)
      Promise.all([p1, p2, p3]).then(res => {
        const [res1, res2, res3] = res
        if (res1.code === 1) {
          const {list, total} = res1.data
          this.tableData = list
          this.page = {
            ...this.page,
            total: total
          }
          if (this.tableData.length > 0) {
            this.tableData.unshift({...res2.data, time: this.$t('合计')})
            this.tableData.unshift({...res3.data, time: this.$t('平均数')})
          }
          this.loading = false
        }
      })

    },
    async tenantChange(value) {
      const res = await selectProduct({adminUserId: value})
      if (res.code === 1) {
        this.$set(this.page, 'productName', null)
        this.productList = res.data
      }
    },
    formatMonthDate(date) {
      const [startDate, endDate] = date || []
      return [startDate, dateFormat(new Date(new Date(endDate).setMonth(new Date(endDate).getMonth() + 1)), 'YYYY-mm')]
    },
    changeWeekValue(value, type) {
      const isoWeek = require('dayjs/plugin/isoWeek')
      dayjs.extend(isoWeek)
      const YY = dayjs().format('YYYY')
      const WW = dayjs(value).isoWeek().toString()
      let dayweek = YY + '-' + WW
      if (WW.length <= 1) {
        // 补0
        dayweek = YY + '-' + ('0' + WW)
      }
      if (value) {
        if (type === 'start') {
          this.page.timeValue[0] = dayweek
        } else {
          this.page.timeValue[1] = dayweek
        }
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    resetSearch() {
      this.page = {
        pageSize: 10,
        pageNum: 1,
        total: 0,
        timeValue: [],
        type: this.page.type
      }
      this.weekStart = ''
      this.weekEnd = ''
      this.getTableData()
    },
    handleClick() {
      if (this.activeName === 'day') {
        this.page.type = 1
      } else if (this.activeName === 'week') {
        this.page.type = 2
      } else {
        this.page.type = 3
      }
      this.page.pageNum = 1
      this.page.pageSize = 10
      this.getTableData()
    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const timeValue = this.activeName === 'day' ? dateFormatSection(this.dayTimeValue) : this.formatMonthDate(this.monthTimeValue)
      const [datetimeStart, datetimeEnd] = timeValue
      const params = {
        ...this.page,
        datetimeStart, datetimeEnd
      };
      delete params.timeValue;
      const res = await financialProfitsExport(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("财务利润表");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
  }
}
</script>

<style scoped>
</style>
x
